#include "newarchive.h"
#include "ui_newarchive.h"


NewArchive::NewArchive(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewArchive)
{
    ui->setupUi(this);


       // 加载项目目录
       load_project_directories();

       setWindowTitle("新建存档");

       // 连接按钮点击事件
       connect(ui->newButton, &QPushButton::clicked, this, &NewArchive::on_copyButton_clicked);
    }

NewArchive::~NewArchive()
{
    delete ui;
}



void NewArchive::load_project_directories() {
   // 加载项目目录列表到ComboBox
   fs::path base_dir = "../station/SOT"; // 项目存放的基础目录

   for (const auto& entry : fs::directory_iterator(base_dir)) {
       if (fs::is_directory(entry)) {
           ui->comboBox->addItem(QString::fromStdString(entry.path().filename().string()));
       }
   }
}


bool NewArchive::copy_directory(const fs::path& source, const fs::path& destination) {
    try {
        // 确保目标文件夹存在
        if (!fs::exists(destination)) {
            fs::create_directory(destination);
        }

        for (const auto& entry : fs::directory_iterator(source)) {
            const auto& path = entry.path();
            auto relative_path = make_relative(path, source);
            std::cout << "source: " << source << std::endl;
            std::cout << "Path: " << path << std::endl;
            std::cout << "relative_path: " << relative_path << std::endl;
            auto target_path = destination/relative_path;

            if (fs::is_directory(path)) {
                if (!copy_directory(path, target_path)) {
                    return false;
                }
            } else if (fs::is_regular_file(path)) {

//                std::cout << "target_path: " << target_path << std::endl;

                std::error_code ec;
                fs::copy(path, target_path, fs::copy_options::overwrite_existing, ec);

                if (ec) {
                    std::cerr << "Error copying file: " << ec.message() << std::endl;
                    return false;
                }
            }
            std::cout << "------------------------ " << std::endl;
        }
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        return false;
    }
}

void NewArchive::on_copyButton_clicked() {

   // 获取选中的项目路径
   QString selected_project = ui->comboBox->currentText();
   fs::path source = "../station/SOT/" + selected_project.toStdString();


   // 获取用户输入的新存档名称
   QString new_name = ui->lineEdit->text();
   if (new_name.isEmpty()) {
       QMessageBox::warning(this, "输入错误", "请填写新存档的名称！");
       return;
   }
   fs::path destination = "../station/SOT/" + new_name.toStdString();
    qDebug()<< new_name;
   // 执行复制操作
   if (copy_directory(source, destination)) {
       this->close();
       QMessageBox::information(this, "成功", "存档创建成功！");
//       QMessageBox::information(this, "提示",
//                                QString("机型名: %1\n存档名: %2\n加载成功!").arg(dirName).arg(archiveName));
   } else {
       QMessageBox::critical(this, "失败", "存档创建失败！");
   }

}

fs::path NewArchive::make_relative(const fs::path& path, const fs::path& source) {
    // 获取两个路径的绝对路径
    fs::path abs_path = fs::canonical(path);
    fs::path abs_source = fs::canonical(source);

    // 如果路径相同，则返回空路径
    if (abs_path == abs_source) {
        return fs::path();
    }

    // 计算相对路径
    fs::path relative;
    auto it1 = abs_path.begin();
    auto it2 = abs_source.begin();

    // 跳过公共前缀
    while (it1 != abs_path.end() && it2 != abs_source.end() && *it1 == *it2) {
        ++it1;
        ++it2;
    }

    // 向上回溯源路径的剩余部分（".."）
    while (it2 != abs_source.end()) {
        relative /= "..";
        ++it2;
    }

    // 将目标路径的剩余部分加到相对路径上
    while (it1 != abs_path.end()) {
        relative /= *it1;
        ++it1;
    }

    return relative;
}

